﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Whir.Common.WebHelper;
using System.Collections.Generic;

public partial class Whir_System_Module_Config_AddType2 : System.Web.UI.Page
{
    protected string Action = "";
    protected int ColumnID = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
        RoleHelper.IsLogin();    //登录判断
        Action = NetRequest.GetQueryString("Action");
        ColumnID = NetRequest.GetQueryInt("ColumnID");

        if (Action == "Modify")
        {
            btnUpdate.Text = "修改";
        }
        else if (Action == "Add")
        {
            btnUpdate.Text = "增加";
        }
        else if (Action == "Delete")
        {
            btnAction();
            return;
        }

        if (!IsPostBack)
        {
            BindTreeDrop("");
        }
    }

    //添加按扭事件
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        btnAction();
    }


    /// <summary>
    /// 绑定栏目树型下拉列表
    /// </summary>    
    protected void BindTreeDrop(string str)
    {
        Whir.Model.Whir_CommonCategory model = new Whir.SQLServerDAL.Whir_CommonCategory().GetModel(ColumnID);
        if (model != null)
        {

            int parentID = GetAllParentID(model.CategoryId);
            Whir.Model.Whir_CommonCategory parentModel = new Whir.BLL.Whir_CommonCategory().GetModel(parentID);

            this.ddlParent.DataValueField = "CategoryId";
            this.ddlParent.DataTextField = "CategoryName";
            Whir.Common.BindHelper.BindDropDownList(this.ddlParent, "Whir_CommonCategory", parentID.ToString(), "", parentModel.CategoryName);
        }
        else
        {
            this.ddlParent.DataValueField = "CategoryId";
            this.ddlParent.DataTextField = "CategoryName";
            Whir.Common.BindHelper.BindDropDownList(this.ddlParent, "Whir_CommonCategory", "0", str, "-- 类别管理 --");
        }
    }

    /// <summary>
    /// 删除栏目编号
    /// </summary>
    private void DeleteColumn(string columnID)
    {
        Whir.SQLServerDAL.Whir_Column bll = new Whir.SQLServerDAL.Whir_Column();
        Whir.Model.Whir_Column model = bll.GetModel(int.Parse(columnID));
        if (model != null)
        {
            bll.Delete(int.Parse(columnID));
        }

        //修改角色表之栏目id
        RoleHelper.UpdateColumnIDs(columnID);
    }

    /// <summary>
    /// 添加方法
    /// </summary>
    private void btnAction()
    {
        int columnID = 0;

        switch (Action)
        {
            case "Add":
                columnID = AddColumn();
                Response.Clear();
                if (columnID == -1)
                    Response.Write("<script>alert('添加类别失败，请正确填写栏目格式！');</script>");
                Response.Write("<script>parent.location='CommonCategory.aspx?op=" + Action + "';</script>");
                break;
        }

        Response.End();
        return;
    }

    /// <summary>
    /// 添加栏目
    /// </summary>
    /// <returns></returns>
    private int AddColumn()
    {
        string addColumns = "";
        try
        {
            //Whir.Model.Whir_Column parentModel = new Whir.BLL.Whir_Column().GetModel(int.Parse(ddlParent.SelectedValue));
            Whir.Model.Whir_CommonCategory parentModel = new Whir.BLL.Whir_CommonCategory().GetModel(int.Parse(ddlParent.SelectedValue));


            string columns = txtColumns.Text;

            columns = columns.Replace("\r\n", "|").Replace("－", "-"); //利用分行符号把栏目区分
            string[] columnCount = columns.Split('|');

            //记录当前类别级别与类别编号
            Dictionary<int, int> dic = new Dictionary<int, int>();
            //记录当前类别级别的个数，用于排序的
            Dictionary<int, int> dicCount = new Dictionary<int, int>();

            for (int i = 0; i < columnCount.Length; i++)
            {
                if (columnCount[i].Trim() != string.Empty)
                {
                    int level = 0;      //当前栏目的级别，根据“-”的个数定义
                    int count = 1;

                    Whir.Model.Whir_CommonCategory model = new Whir.Model.Whir_CommonCategory();

                    string columnName = columnCount[i];
                    if (columnName.Contains("-"))
                    {
                        //获取“-”出现的个数，出现的次数代表级别
                        level = GetCount(columnCount[i], "-");

                        int parentID = 0;
                        //获取该级别是否存在
                        if (!dic.TryGetValue(level - 1, out parentID))
                        {
                            throw new Exception();
                        }

                        if (dicCount.ContainsKey(level))
                            dicCount[level] = dicCount[level] + 1;
                        else
                            dicCount[level] = 1;

                        model.ParentId = parentID;
                        model.CategoryName = columnCount[i].Replace("-", "").Trim();
                    }
                    else //添加一级子栏目
                    {
                        level = 0;

                        if (dicCount.ContainsKey(level))
                            dicCount[level] = dicCount[level] + 1;
                        else
                            dicCount[level] = GetMxaSort(ddlParent.SelectedValue);

                        model.ParentId = int.Parse(this.ddlParent.SelectedValue);
                        model.CategoryName = columnCount[i];
                    }

                    model.Sort = dicCount[level];
                    model.CreateDate = DateTime.Now;
                    model.CreateUserID = RoleHelper.GetAdminID();
                    model.UpdateDate = model.CreateDate;
                    model.UpdateUserID = model.CreateUserID;

                    int cloumnID = new Whir.SQLServerDAL.Whir_CommonCategory().Add(model);

                    //把当前栏目编号所对应的级别添加到记录中
                    //当前级别存在
                    if (dic.ContainsKey(level))
                        dic[level] = cloumnID;
                    else
                        dic.Add(level, cloumnID);

                    //把当前栏目记录，回滚的时候用到
                    addColumns += cloumnID + ",";
                }
            }
            return int.Parse(this.ddlParent.SelectedValue);
        }
        catch
        {
            if (addColumns.Trim() != string.Empty)
            {
                string[] strTemp = addColumns.Split(',');
                for (int i = 0; i < strTemp.Length; i++)
                {
                    if (strTemp[i] != string.Empty)
                        DeleteColumn(strTemp[i]);
                }
            }

            return -1;
        }
    }

    /// <summary>
    /// 获取该栏目的父级栏目的子栏目个数
    /// </summary>
    /// <param name="parentID">栏目编号</param>
    protected int GetMxaSort(string parentID)
    {
        string sql = String.Format("SELECT COUNT(1) + 1 FROM Whir_CommonCategory WHERE ParentId = {0}", parentID);
        object obj = Whir.SQLServerDAL.DbHelperSQL.GetSingle(sql);

        return obj != null ? Convert.ToInt32(obj) : 1;
    }

    /// <summary>
    /// 获取字符串中字符出现的个数
    /// </summary>
    /// <param name="str1">字符串</param>
    /// <param name="str2">字符</param>
    /// <returns>字符出现的个数</returns>
    protected int GetCount(string str1, string str2)
    {
        return (str1.Length - str1.Replace(str2, "").Length);
    }

    /// <summary>
    /// 获取该类别编号的最终父级编号
    /// </summary>
    /// <param name="categoryID">类别编号</param>
    private int GetAllParentID(int categoryID)
    {
        int parentID = 0;
        Whir.Model.Whir_CommonCategory model = new Whir.SQLServerDAL.Whir_CommonCategory().GetModel(categoryID);
        if (model != null)
        {
            if (model.ParentId != 0)
                parentID = GetAllParentID(model.ParentId);
            else
                parentID = categoryID;
        }

        return parentID;
    }
}
